﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenServe.Net.Library.Interfaces;
using OpenServe.Net.Client;
using OpenServe.Net.Library.Extentions;
using System.Threading;
using System.Diagnostics;


namespace OpenServe.Net.Messaging.Server {
    using OpenServe.Net.Server;
    using System.Reflection;
    using System.Threading.Tasks;
    public class DefaultHandler : BaseHandler {

        public DefaultHandler(Server.Client _parent) : base(_parent, "DefaultHandler") {}

        public string ServerVersion(object o) {
            var msg = o as Message;
            msg.Header.Operation += "_Callback";
            msg.Header.Destination = msg.Header.Source;
            msg.Header.Source = new Guid();
            msg.Body = "OpenServe.Net - " + Assembly.GetCallingAssembly().GetName().Version.ToString(4);
            Send(msg);
            return null;
        }

        public void SetName(object o) {
            var m = o as Message;
            var p = Parent as Server.Client;
            p.Name = m.Body.ToString();
            m.Header.Operation += "_Callback";
            m.Header.Destination = m.Header.Source;
            m.Header.Source = new Guid();
            m.Body = p.GUID.ToString();
            Send(m);
        }
    }
}

namespace OpenServe.Net.Messaging.Client {
    using OpenServe.Net.Client;
    using OpenServe.Net.Library.Utils;
    using System.Threading.Tasks;
    public class DefaultHandler : BaseHandler {

        ManualResetEvent mreServerVersion = new ManualResetEvent(false);
        string serverVersion = "";

        public DefaultHandler(Client _parent) : base(_parent, "DefaultHandler") {}

        public string ServerVersion(object o = null) {
            var msg = new Message {
                Header = new Header { Source = Parent.GUID, Operation = Utils.CurrentOperation, ContainingType = typeof(string) },
                Body = ""
            };
            SendAndWait(msg, mreServerVersion);
            return serverVersion;
        }

        public void ServerVersion_Callback(Message msg) {
            serverVersion = msg.Body.ToString();
            mreServerVersion.Set();
        }

        public void SetName(object o) {
            var msg = new Message {
                Header = new Header { Source = Parent.GUID, Operation = Utils.CurrentOperation, ContainingType = typeof(string) },
                Body = Parent.Name ?? ""
            };
            Send(msg);
        }

        public void SetName_Callback(Message msg) {
            Parent.GUID = Guid.Parse(msg.Body.ToString());
        }
    }
}
